<template>
  <div id="commentManagePage">
    <a-flex justify="space-between">
      <h2>评论管理</h2>
    </a-flex>

    <div style="margin-bottom: 20px"></div>

    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从评论内容搜索"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片ID" name="pictureId">
        <a-input-number
          v-model:value="searchParams.pictureId"
          placeholder="请输入图片ID"
          :min="1"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="用户ID" name="userId">
        <a-input-number
          v-model:value="searchParams.userId"
          placeholder="请输入用户ID"
          :min="1"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="COMMENT_REVIEW_STATUS_OPTIONS"
          placeholder="请选择审核状态"
          style="min-width: 120px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 20px"></div>

    <!--表格-->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <!-- 评论内容 -->
        <template v-if="column.dataIndex === 'content'">
          <div style="max-width: 300px; word-break: break-all;">
            {{ record.content }}
          </div>
        </template>

        <!-- 用户信息 -->
        <template v-if="column.dataIndex === 'user'">
          <div v-if="record.user">
            <div>{{ record.user.userName }}</div>
            <div style="color: #999; font-size: 12px;">@{{ record.user.userAccount }}</div>
          </div>
        </template>

        <!-- 审核状态 -->
        <template v-if="column.dataIndex === 'reviewStatus'">
          <a-tag :color="getReviewStatusColor(record.reviewStatus)">
            {{ COMMENT_REVIEW_STATUS_MAP[record.reviewStatus] }}
          </a-tag>
        </template>

        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewInfo'">
          <div v-if="record.reviewMessage">审核信息：{{ record.reviewMessage }}</div>
          <div v-if="record.reviewTime">审核时间：{{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
        </template>

        <!-- 创建时间 -->
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <!-- 操作 -->
        <template v-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              v-if="record.reviewStatus !== COMMENT_REVIEW_STATUS_ENUM.PASS"
              type="link"
              @click="handleReview(record, COMMENT_REVIEW_STATUS_ENUM.PASS)"
            >
              通过
            </a-button>
            <a-button
              v-if="record.reviewStatus !== COMMENT_REVIEW_STATUS_ENUM.REJECT"
              type="link"
              danger
              @click="handleReview(record, COMMENT_REVIEW_STATUS_ENUM.REJECT)"
            >
              拒绝
            </a-button>
            <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 审核对话框 -->
    <a-modal
      v-model:visible="reviewModalVisible"
      title="审核评论"
      @ok="handleReviewConfirm"
      @cancel="handleReviewCancel"
    >
      <a-form :model="reviewForm">
        <a-form-item label="审核操作">
          <a-radio-group v-model:value="reviewForm.reviewStatus">
            <a-radio :value="COMMENT_REVIEW_STATUS_ENUM.PASS">通过</a-radio>
            <a-radio :value="COMMENT_REVIEW_STATUS_ENUM.REJECT">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审核信息">
          <a-textarea
            v-model:value="reviewForm.reviewMessage"
            placeholder="请输入审核信息（可选）"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deleteCommentUsingPost,
  listCommentByPageUsingPost,
  reviewCommentUsingPost
} from '@/api/commentController.ts'
import dayjs from 'dayjs'
import {
  COMMENT_REVIEW_STATUS_ENUM,
  COMMENT_REVIEW_STATUS_MAP,
  COMMENT_REVIEW_STATUS_OPTIONS
} from '../../constants/comment.ts'

/**
 * 表格列定义
 */
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '评论内容',
    dataIndex: 'content',
    ellipsis: true,
  },
  {
    title: '图片ID',
    dataIndex: 'pictureId',
    width: 100,
  },
  {
    title: '用户信息',
    dataIndex: 'user',
  },
  {
    title: '审核状态',
    dataIndex: 'reviewStatus',
    width: 100,
  },

  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

/**
 * 表单功能实现
 */
// 数据
const dataList = ref([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.CommentQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})

// 获取数据
const fetchData = async () => {
  const res = await listCommentByPageUsingPost(searchParams)

  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data ?? []
    total.value = res.data.data ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 搜索
const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 审核状态颜色
const getReviewStatusColor = (status: number) => {
  switch (status) {
    case COMMENT_REVIEW_STATUS_ENUM.REVIEWING:
      return 'orange'
    case COMMENT_REVIEW_STATUS_ENUM.PASS:
      return 'green'
    case COMMENT_REVIEW_STATUS_ENUM.REJECT:
      return 'red'
    default:
      return 'default'
  }
}

// 审核相关
const reviewModalVisible = ref(false)
const currentReviewRecord = ref<API.CommentVO | null>(null)
const reviewForm = reactive({
  reviewStatus: COMMENT_REVIEW_STATUS_ENUM.PASS,
  reviewMessage: '',
})

// 打开审核对话框
const handleReview = (record: API.CommentVO, reviewStatus?: number) => {
  currentReviewRecord.value = record
  if (reviewStatus) {
    reviewForm.reviewStatus = reviewStatus
    reviewForm.reviewMessage = reviewStatus === COMMENT_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
    handleReviewConfirm()
  } else {
    reviewForm.reviewStatus = COMMENT_REVIEW_STATUS_ENUM.PASS
    reviewForm.reviewMessage = ''
    reviewModalVisible.value = true
  }
}

// 确认审核
const handleReviewConfirm = async () => {
  if (!currentReviewRecord.value) {
    return
  }

  const res = await reviewCommentUsingPost({
    id: currentReviewRecord.value.id,
    reviewStatus: reviewForm.reviewStatus,
    reviewMessage: reviewForm.reviewMessage,
  })

  if (res.data.code === 0) {
    message.success('审核操作成功')
    reviewModalVisible.value = false
    fetchData()
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}

// 取消审核
const handleReviewCancel = () => {
  reviewModalVisible.value = false
  currentReviewRecord.value = null
  reviewForm.reviewMessage = ''
}

// 删除评论
const doDelete = async (id: number) => {
  const confirm = window.confirm('确定删除这条评论吗？')
  if (!confirm) {
    return
  }

  const res = await deleteCommentUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}
</script>

<style scoped>
#commentManagePage {
  padding: 20px;
}

.ant-table-cell {
  word-break: break-word;
}
</style>
